//
//  AddTwoNumbers.swift
//  LeetCodeDemo
//
//  Created by 杨冬武 on 2021/4/24.
//

import Foundation

class AddTwoNumbers {
    
    
    /*
     递归
     */
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        return addTwoNumbersHelper(l1, l2, 0)
    }
    
    func addTwoNumbersHelper(_ l1: ListNode?, _ l2: ListNode?, _ carry: Int) -> ListNode? {
        if l1 == nil && l2 == nil {
            return carry == 0 ? nil : ListNode(carry)
        }
        var temp = carry
        var node1 = l1, node2 = l2
        if let val1 = l1?.val {
            temp += val1
            node1 = node1?.next
        }
        if let val2 = l2?.val {
            temp += val2
            node2 = node2?.next
        }
        return ListNode(temp % 10, addTwoNumbersHelper(node1, node2, temp / 10))
    }
}
